import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:gluz/app/data/country_entity.dart';
import 'package:gluz/app/data/shop/shop_list_entity.dart';
import 'package:gluz/app/utils/colors.dart';

import '../controllers/search_controller.dart' as search;

class SearchView extends GetView<search.SearchController> {
  const SearchView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: _buildAppBar(),
      body: Column(
        children: [
          _buildSearchInput(),
          _buildSearchHistory(),
          Expanded(child: _buildSearchResults()),
        ],
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: Colors.white,
      elevation: 0,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios, color: Colors.black),
        onPressed: controller.onBackTap,
      ),
      title: Text(
        '搜索'.tr,
        style: const TextStyle(
          color: Colors.black,
          fontSize: 18,
          fontWeight: FontWeight.bold,
        ),
      ),
      centerTitle: true,
    );
  }

  Widget _buildSearchInput() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: SizedBox(
        height: 40,
        child: TextField(
          controller: controller.searchController,
          decoration: InputDecoration(
            hintText: '搜索'.tr,
            hintStyle: TextStyle(color: Colors.grey[500]),
            prefixIcon: Icon(Icons.search, color: Colors.grey[500], size: 24),
            suffixIcon: ElevatedButton(
              onPressed: () => controller.performSearch(),
              style: ElevatedButton.styleFrom(
                backgroundColor: AppColors.color_278AFF,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 8,
                ),
                minimumSize: Size.zero,
                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
              ),
              child: Text(
                '搜索'.tr,
                style: const TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            filled: true,
            fillColor: Colors.grey[100],
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(22),
              borderSide: BorderSide.none,
            ),
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 0,
            ),
            isDense: true,
          ),
          onSubmitted: (value) => controller.performSearch(),
        ),
      ),
    );
  }

  Widget _buildSearchHistory() {
    return Obx(() {
      if (controller.searchHistory.isEmpty) {
        return const SizedBox.shrink();
      }

      return Container(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 历史记录标签
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '搜索历史'.tr,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.black,
                  ),
                ),
                if (controller.searchHistory.isNotEmpty)
                  GestureDetector(
                    onTap: controller.clearSearchHistory,
                    child: Text(
                      '清除历史记录'.tr,
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                        decoration: TextDecoration.underline,
                      ),
                    ),
                  ),
              ],
            ),
            const SizedBox(height: 12),
            // 历史记录标签
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: controller.searchHistory.map((keyword) {
                return GestureDetector(
                  onTap: () => controller.onHistoryTap(keyword),
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 6,
                    ),
                    decoration: BoxDecoration(
                      color: AppColors.color_278AFF.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(16),
                      border: Border.all(
                        color: AppColors.color_278AFF.withOpacity(0.3),
                        width: 1,
                      ),
                    ),
                    child: Text(
                      keyword,
                      style: TextStyle(
                        fontSize: 12,
                        color: AppColors.color_278AFF,
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
            const SizedBox(height: 16),
          ],
        ),
      );
    });
  }

  Widget _buildSearchResults() {
    return Obx(() {
      if (!controller.hasSearched.value) {
        return _buildEmptyState();
      }

      if (controller.isSearching.value) {
        return const Center(child: CircularProgressIndicator());
      }

      if (controller.searchResults.isEmpty) {
        return _buildNoResultsState();
      }

      return _buildProductList();
    });
  }

  Widget _buildEmptyState() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Image.asset('assets/images/shop/shop_search_empty.png', width: 150,),
        const SizedBox(height: 5),
        Text(
          '暂无搜索信息'.tr,
          style: TextStyle(fontSize: 12, color: Colors.grey[600]),
        ),
      ],
    );
  }

  Widget _buildNoResultsState() {
    return _buildEmptyState();
  }

  Widget _buildProductList() {
    return NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification scrollInfo) {
        if (scrollInfo.metrics.pixels == scrollInfo.metrics.maxScrollExtent &&
            !controller.isLoadingMore) {
          controller.loadMoreResults();
        }
        return false;
      },
      child: GridView.builder(
        padding: const EdgeInsets.all(16),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 0.75,
          crossAxisSpacing: 12,
          mainAxisSpacing: 12,
        ),
        itemCount:
            controller.searchResults.length + (controller.hasMoreData ? 1 : 0),
        itemBuilder: (context, index) {
          if (index == controller.searchResults.length) {
            return const Center(child: CircularProgressIndicator());
          }
          return _buildProductItem(controller.searchResults[index]);
        },
      ),
    );
  }

  Widget _buildProductItem(ShopListEntity product) {
    return InkWell(
      onTap: () => controller.onProductTap(product),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 4,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 商品图片
            Container(
              height: 100,
              child: ClipRRect(
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(8),
                  topRight: Radius.circular(8),
                ),
                child: CachedNetworkImage(
                  imageUrl: product.getMainPicUrl(),
                  fit: BoxFit.cover,
                  width: double.infinity,
                  placeholder: (context, url) => Container(
                    color: Colors.grey[200],
                    child: const Center(child: CircularProgressIndicator()),
                  ),
                  errorWidget: (context, url, error) => Container(
                    color: Colors.grey[200],
                    child: const Icon(Icons.error),
                  ),
                ),
              ),
            ),
            // 商品信息
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(8),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 商品名称
                    Expanded(
                      child: Text(
                        product.skuName,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w500,
                          color: Colors.black,
                        ),
                      ),
                    ),
                    const SizedBox(height: 4),
                    // 价格和浏览量
                    Row(
                      children: [
                        Text(
                          '¥${product.salesPrice}',
                          style: const TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.bold,
                            color: Colors.orange,
                          ),
                        ),
                        const Spacer(),
                        Icon(
                          Icons.visibility,
                          size: 12,
                          color: AppColors.color_8C8C8C,
                        ),
                        const SizedBox(width: 4),
                        Text(
                          '${product.pageView}+',
                          style: TextStyle(
                            fontSize: 10,
                            color: AppColors.color_8C8C8C,
                          ),
                        ),
                      ],
                    ),

                    const SizedBox(height: 5),
                    Image.asset('assets/images/shop/shop_dot_line.png'),
                    const SizedBox(height: 5),
                    // 用户信息
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        CircleAvatar(
                          foregroundImage: CachedNetworkImageProvider(
                            product.userImg,
                          ),
                          radius: 10,
                        ),
                        const SizedBox(width: 4),
                        Expanded(
                          child: Row(
                            children: [
                              Text(
                                product.userName,
                                style: TextStyle(
                                  fontSize: 10,
                                  color: AppColors.color_8C8C8C,
                                ),
                              ),
                              const SizedBox(width: 5),
                              CachedNetworkImage(
                                imageUrl: product.getMemberLevelUrl(),
                                width: 10,
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(width: 5),
                        CircleAvatar(
                          foregroundImage: AssetImage(
                            CountryEntity.getCountryImage(
                              product.userCountry,
                            ),
                          ),
                          radius: 10,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
